import { withRouter } from 'react-router-dom';
import PropTypes from 'prop-types';
import React, { PureComponent as Component } from 'react';
import { Tree, Row, Col, Button, Modal, Input, message } from 'antd';
import { jsonToBody, bodyToJson, onAddBrother, delEmpty, checkImportJson } from './Tools/MethodBodyFunc.js';
const { TreeNode } = Tree;
const { TextArea } = Input;

/**
 * 暂定
 * 数据模块: dataSource, 为Array类型，其中children为子节点集合,dataSource.children 也是Array类型
 * 数据验证模块 TODO
 * 树形判断 getIsTree(data), 返回true|false
 * 基础组件: getCellComponent(data, indexArray, form, state, setState, treeIndex, updateModalData)
 */
@withRouter
export default class ParamsTree extends Component {

  initState(dataSource) {
    return {
      isEdit: false,
      dataSource: dataSource,
      expandedKeys: [],
      editModalData: {
        isShow: false,
        data: '',
        indexArray: []
      }
    };  // 用于刷新界面
  }

  static propTypes = {
    dataSource: PropTypes.array,
    form: PropTypes.object,
    getIsTree: PropTypes.func,
    getCellComponent: PropTypes.func,
    getIndexArray: PropTypes.func,
    getFormIndex: PropTypes.func,
    treeIndex: PropTypes.string,
    topButName: PropTypes.string,
    updateModalData: PropTypes.func
  };

  constructor(props) {
    super(props);
    this.state = this.initState(props.dataSource);
  }

  onExpand = (expandedKeys) => {
    this.setState({expandedKeys: expandedKeys})
  }

  onImportJsonClick = () => {
    this.setState({
      editModalData: {
        data: bodyToJson(this.state.dataSource, 2),
        indexArray: [this.props.treeIndex],
        isShow: true
      }
    })
  }

  onEditModalOk = () => {
    let tempModalData = this.state.editModalData
    let checkResult = checkImportJson(tempModalData.data)
    if (checkResult.available) {
      let cloneDataSource = this.state.dataSource.concat();
      let targetValue = cloneDataSource;
      tempModalData.indexArray.map((value, index) => {
        if (value === this.props.treeIndex) {
          if (index === tempModalData.indexArray.length - 1) {
            cloneDataSource = jsonToBody(tempModalData.data)
          }
        } else if (index === tempModalData.indexArray.length - 1) {
          targetValue[value] = jsonToBody(tempModalData.data)
          // TODO 删除str前多少个字符为某个值的expendedKeys
        } else {
          targetValue = targetValue[value];
        }
      });
      this.setState({
        dataSource: cloneDataSource,
        editModalData: {
          isShow: false,
          data: '',
          indexArray: []
        }
      })
    } else {
      message.error(checkResult.message)
    }
  }

  onEditModalCancel = () => {
    this.setState({
      editModalData: {isShow: false}
    })
  }

  onEditModalChange = (e) => {
    this.setState({
      editModalData: Object.assign({}, this.state.editModalData, {data: e.target.value})
    })
  }

  getFieldsRender = (getData) => {
    if (getData == 'undefined') {
      return (
        <Row>ERROR</Row>
      );
    } else if (getData.length == 0) {
      return (
        <div>
          <Row>
            <Modal
              title="批量添加参数"
              width={680}
              visible={this.state.editModalData.isShow}
              onOk={()=>this.onEditModalOk()}  
              onCancel={()=>this.onEditModalCancel()}
              okText="导入"
            >
              <div>
                <TextArea
                  placeholder="请输入..."
                  autosize={{ minRows: 6, maxRows: 10 }}
                  value={this.state.editModalData.data}
                  onChange={(e)=>this.onEditModalChange(e)}
                />
              </div>
            </Modal>
          </Row>
          <Row type="flex" justify="space-around">
            <Col span={24}>
              <div>
                <Button size="small" type="primary" onClick={() => onAddBrother([this.props.treeIndex], this.state, this.setState.bind(this), this.props.treeIndex)}>
                  {this.props.topButName}
                </Button>
                &emsp;
                <Button size="small" type="primary" onClick={() => this.onImportJsonClick()}>
                  导入json
                </Button>
              </div>
            </Col>
          </Row>
          <Row>数据为空</Row>
        </div>
      );
    } else {
      return (
        <div>
          <Row>
            <Modal
              title="批量添加参数"
              width={680}
              visible={this.state.editModalData.isShow}
              onOk={()=>this.onEditModalOk()}  
              onCancel={()=>this.onEditModalCancel()}
              okText="导入"
            >
              <div>
                <TextArea
                  placeholder="请输入..."
                  autosize={{ minRows: 6, maxRows: 10 }}
                  value={this.state.editModalData.data}
                  onChange={(e)=>this.onEditModalChange(e)}
                />
              </div>
            </Modal>
          </Row>
          <Row type="flex" justify="space-around">
            <Col span={24}>
              <div>
                <Button size="small" type="primary" onClick={() => onAddBrother([this.props.treeIndex], this.state, this.setState.bind(this), this.props.treeIndex)}>
                  {this.props.topButName}
                </Button>
                &emsp;
                <Button size="small" type="primary" onClick={() => this.onImportJsonClick()}>
                  导入json
                </Button>
              </div>
            </Col>
          </Row>
          <Tree
            blockNode
            onExpand={this.onExpand}
            expandedKeys={this.state.expandedKeys}
            onDragEnter={this.onDragEnter}
            onDrop={this.onDrop}
            key={this.props.treeIndex + '_tree'}
          >
            {this.getTreeNode(getData, [this.props.treeIndex])}
          </Tree>
        </div>
      );
    }
  }
  /**
   * @param:children_data:Array
   */
  getTreeNode = (children_data, indexArray) => {
    const data = children_data;
    const { getIsTree, getCellComponent, getFormIndex, form } = this.props;
    if (data == 'undefined') {
      return (
        // jctest
        <Row>ERROR2</Row>
      );
    } else if (data.length === 0) {
      return;
    } else {
      let ret = data.map((value, index) => {
        let curIndexArray = indexArray.concat(index);
        return (
          <TreeNode className="col-field-tree" span="24" key={getFormIndex(curIndexArray)} title={getCellComponent(value, curIndexArray, form, this.state, this.setState.bind(this), this.props.treeIndex)}>
            {getIsTree(value) && this.getTreeNode(value.children, curIndexArray.concat('children'))}
          </TreeNode>
        );
      })
      ret = delEmpty(ret);
      return ret;
    }
  }

  render() {
    return this.getFieldsRender(jsonToBody(bodyToJson(this.state.dataSource)));
  }
}
